package pl.wroc.pwr.docs.repos.webapp.web;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.sql.DataSource;

import pl.wroc.pwr.docs.repos.webapp.repo.DocumentDao;
import pl.wroc.pwr.docs.repos.webapp.web.Message.STATUS;

@WebServlet(urlPatterns="/document-upload")
@MultipartConfig
public class DocumentUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		for (Part part : request.getParts()) {
			
			String filename = getFileName(part);
			
			if(filename == null)
				continue;
			
			InputStream fileStream = null;
			MessageQueue messages = ((MessageQueue) request.getSession().getAttribute("messages"));
			ServletContext context = getServletContext();
			DataSource ds = (DataSource) context.getAttribute("connectionPool");
			Connection con = null;
			
			try {			
				fileStream = part.getInputStream();
				con = ds.getConnection();
				DocumentDao dao = new DocumentDao(con);
				int id = dao.addDocument(filename, fileStream);
				System.out.println(id);
				dao.addIndexedContent(id, dao.getContent(id, 1000));
				dao.addMetadata(id, dao.getMetadata(id));
				messages.push( new Message(STATUS.SUCCESS, "Dokument " +filename+ " został dodany pomyślnie.") );
				
			} catch (Exception ex) {
				ex.printStackTrace();
				messages.push( new Message(STATUS.ERROR, "Nie udało się dodać dokumentu " +filename+ '.'));
				
			} finally {
				if (fileStream != null) {
					fileStream.close();
				}
				if(con != null){
					try {
						con.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}
		
		response.sendRedirect("/index.jsp#add");
	}

	private String getFileName(final Part part) {
		//final String partHeader = part.getHeader("content-disposition");

		for (String content : part.getHeader("content-disposition").split(";")) {
			if (content.trim().startsWith("filename")) {
				return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
			}
		}
		return null;
	}
}
